package com.gzhryc.shared_device.oem.h5.agent.controllers.api.v1.team;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.enums.EOperatorType;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.common.payment.dao.db.PayAccountGroup;
import com.gzhryc.shared_device.common.payment.services.PayAccountGroupService;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.code.user.dao.db.UserTransferMoneyOrder;
import com.gzhryc.shared_device.oem.code.user.dao.enums.UserTransferMoneyOrderEnum;
import com.gzhryc.shared_device.oem.code.user.services.UserTransferMoneyOrderService;
import com.gzhryc.shared_device.oem.code.user.services.dto.UserTransferMoneyOrderSearch;
import com.gzhryc.shared_device.oem.h5.agent.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.h5.agent.LoginUser;
import com.gzhryc.shared_device.oem.h5.agent.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.UserTransferMoneyOrderFinishRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.UserTransferMoneyOrderInfoRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.UserTransferMoneyOrderInfoResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.UserTransferMoneyOrderListRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.UserTransferMoneyOrderListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.UserTransferMoneyOrderRejecRequest;

public class TeamUserTransferMoneyOrderController {

	@Route(value = "/agent/api/v1/team/user/transfer_money_order/list.data")
	public UserTransferMoneyOrderListResponse listData(HttpServletRequest request) {
		UserTransferMoneyOrderListResponse apiResp = new UserTransferMoneyOrderListResponse(ClientAPICodeConstants.NULL_DATA,
				"暂无数据");
		UserTransferMoneyOrderListRequest apiReq = WebUtils.getJsonRequest(request,
				UserTransferMoneyOrderListRequest.class);
		if (apiReq != null) {
			LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
			if (loginUser != null && ERoleType.Agent.index().equals(loginUser.getRoleType())) {
				List<PayAccountGroup> accountGroupList = PayAccountGroupService.self().findByUserId(loginUser.getId());
				if (accountGroupList != null && accountGroupList.size() > 0) {
					List<Long> accountGroupIds = new ArrayList<Long>();
					for (PayAccountGroup accountGroup : accountGroupList) {
						accountGroupIds.add(accountGroup.getId());
					}

					Integer pageNo = apiReq.getBody().getPageNo() == null ? 1 : apiReq.getBody().getPageNo();
					Integer pageLimit = apiReq.getBody().getPageLimit() == null ? 1 : WebConstants.PAGE_LIMIT;

					UserTransferMoneyOrderSearch search = new UserTransferMoneyOrderSearch();
					search.setTradeNo(apiReq.getBody().getTrim());
					search.setAccountGroupIds(accountGroupIds);
					if (apiReq.getBody().getState() != null && apiReq.getBody().getState() > 0) {
						if (apiReq.getBody().getState() == 1) {
							search.setState(UserTransferMoneyOrderEnum.State.Check.index());
						} else if (apiReq.getBody().getState() == 2) {
							search.setState(UserTransferMoneyOrderEnum.State.Success.index());
						} else if (apiReq.getBody().getState() == 3) {
							search.setState(UserTransferMoneyOrderEnum.State.Reject.index());
						} else {
							return apiResp;
						}
					}

					List<UserTransferMoneyOrder> transferMoneyOrderList = UserTransferMoneyOrderService.self()
							.findJoinBySearch(search, pageNo, pageLimit);
					if (transferMoneyOrderList != null && transferMoneyOrderList.size() > 0) {
						apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
						apiResp.getBody().setItems(new ArrayList<>());

						for (UserTransferMoneyOrder order : transferMoneyOrderList) {
							UserTransferMoneyOrderListResponse.Item item = new UserTransferMoneyOrderListResponse.Item();
							item.setTradeNo(order.getTradeNo());
							item.setAccountGroupId(order.getAccountGroupId());
							item.setAccountGroupName(order.getAccountGroupName());
							item.setUserId(order.getUserId());
							item.setUserName(order.getUserName());
							item.setUserPhone(order.getUserPhone());
							item.setMoneyStr(order.getMoneyStr());
							item.setProfitProportion(order.getProfitProportion());
							item.setReceiptMoneyStr(order.getReceiptMoneyStr());
							item.setHandleType(order.getHandleType());
							item.setHandleTypeName(order.getHandleTypeName());
							item.setHandleDate(order.getHandleDate());
							item.setRejectNote(order.getRejectNote());
							item.setState(order.getState());
							item.setStateName(order.getStateName());
							item.setCreateDate(order.getCreateDate());
							apiResp.getBody().getItems().add(item);
						}
					}
				}
			}
		}
		return apiResp;
	}

	@Route(value = "/agent/api/v1/team/user/transfer_money_order/info.data")
	public UserTransferMoneyOrderInfoResponse info(HttpServletRequest request) {
		UserTransferMoneyOrderInfoResponse apiResp = new UserTransferMoneyOrderInfoResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
		UserTransferMoneyOrderInfoRequest apiReq = WebUtils.getJsonRequest(request,UserTransferMoneyOrderInfoRequest.class);
		if (apiReq != null) {
			LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
			if (loginUser != null && ERoleType.Agent.index().equals(loginUser.getRoleType())) {
				UserTransferMoneyOrder order = UserTransferMoneyOrderService.self()
						.getJoinByTradeNo(apiReq.getBody().getTradeNo());
				if (order != null) {
					PayAccountGroup accountGroup = PayAccountGroupService.self().getById(order.getAccountGroupId());
					if (accountGroup != null && accountGroup.getUserId() != null && accountGroup.getUserId().equals(loginUser.getId())) {
						String resDomain = PropertyTools.get().getString("resDomain");
						if (StringTools.isNotBlank(order.getReceivingQrcode())) {
							order.setReceivingQrcode(WebUtils.setHttpDomain(resDomain, order.getReceivingQrcode()));
						}
						if(StringTools.isNotBlank(order.getProofImg())) {
							order.setProofImg(WebUtils.setHttpDomain(resDomain, order.getProofImg()));
						}
						
						apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
						apiResp.getBody().setTradeNo(order.getTradeNo());
						apiResp.getBody().setAccountGroupId(order.getAccountGroupId());
						apiResp.getBody().setAccountGroupName(order.getAccountGroupName());
						apiResp.getBody().setUserId(order.getUserId());
						apiResp.getBody().setUserName(order.getUserName());
						apiResp.getBody().setUserPhone(order.getUserPhone());
						apiResp.getBody().setMoneyStr(order.getMoneyStr());
						apiResp.getBody().setProfitProportion(order.getProfitProportion());
						apiResp.getBody().setReceiptMoneyStr(order.getReceiptMoneyStr());
						apiResp.getBody().setPayType(order.getPayType());
						apiResp.getBody().setPayTypeName(order.getPayTypeName());
						apiResp.getBody().setReceivingType(order.getReceivingType());
						apiResp.getBody().setReceivingTypeName(order.getReceivingTypeName());
						apiResp.getBody().setReceivingQrcode(order.getReceivingQrcode());
						apiResp.getBody().setHandleType(order.getHandleType());
						apiResp.getBody().setHandleTypeName(order.getHandleTypeName());
						apiResp.getBody().setProofImg(order.getProofImg());
						apiResp.getBody().setHandleDate(order.getHandleDate());
						apiResp.getBody().setOperator(order.getOperator());
						apiResp.getBody().setRejectNote(order.getRejectNote());
						apiResp.getBody().setState(order.getState());
						apiResp.getBody().setStateName(order.getStateName());
						apiResp.getBody().setUpdateDate(order.getUpdateDate());
						apiResp.getBody().setCreateDate(order.getCreateDate());
					}
				}
			}
		}
		return apiResp;
	}
	
	@Route(value = { "/agent/api/v1/team/user/transfer_money_order/reject.do" })
    public DefaultAPIResponse doReject(HttpServletRequest request, HttpSession session) {
		DefaultAPIResponse result = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR,"处理失败，请稍后再试");
    	UserTransferMoneyOrderRejecRequest apiReq = WebUtils.getJsonRequest(request,UserTransferMoneyOrderRejecRequest.class);
		if (apiReq != null) {
			LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
	    	if(loginUser == null) {
	            result.setCode(ClientAPICodeConstants.LOGIN_OVERDUE, "登录过期，请重新登录");
	            return result;
	        }
	        if(StringTools.isNotBlank(apiReq.getBody().getTradeNo()) && StringTools.isNotBlank(apiReq.getBody().getOperateNote())) {
	        	UserTransferMoneyOrder order = UserTransferMoneyOrderService.self().getByTradeNo(apiReq.getBody().getTradeNo());
			    if(order != null) {
		        	PayAccountGroup accountGroup = PayAccountGroupService.self().getById(order.getAccountGroupId());
		        	if(accountGroup != null && accountGroup.getUserId() != null 
		        			&& accountGroup.getUserId().equals(loginUser.getId())) {
			            OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE,WebConstants.PROGRAM_TYPE_NAME);
			            operateInfo.setOperator( EOperatorType.Agent.index(),loginUser.getFullName());
			            operateInfo.setOperateNote(apiReq.getBody().getOperateNote());
			            try {
			                if (UserTransferMoneyOrderService.self().reject(apiReq.getBody().getTradeNo(),operateInfo)) {
			                    result.setCode(DtoConstants.SUCCESS, null);
			                }
			            } catch (LogicException e) {
			                result.setMsg(e.getMessage());
			            }
		        	}
			    }
	        }
		}
        return result;
    }
	
	@Route(value = { "/agent/api/v1/team/user/transfer_money_order/finish.do" })
    public DefaultAPIResponse doSuccess(HttpServletRequest request, HttpSession session) {
		DefaultAPIResponse result = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR,"处理失败，请稍后再试");
    	UserTransferMoneyOrderFinishRequest apiReq = WebUtils.getJsonRequest(request,UserTransferMoneyOrderFinishRequest.class);
		if (apiReq != null) {
			LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
	    	if(loginUser == null) {
	            result.setCode(ClientAPICodeConstants.LOGIN_OVERDUE, "登录过期，请重新登录");
	            return result;
	        }
    
	        if(StringTools.isNotBlank(apiReq.getBody().getTradeNo()) && apiReq.getBody().getHandleType() != null) {
	        	UserTransferMoneyOrder order = UserTransferMoneyOrderService.self().getByTradeNo(apiReq.getBody().getTradeNo());
			    if(order != null) {
		        	PayAccountGroup accountGroup = PayAccountGroupService.self().getById(order.getAccountGroupId());
		        	if(accountGroup != null && accountGroup.getUserId() != null 
		        			&& accountGroup.getUserId().equals(loginUser.getId())) {
			            OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE,WebConstants.PROGRAM_TYPE_NAME);
			            operateInfo.setOperator( EOperatorType.Agent.index(),loginUser.getFullName());
			            if(UserTransferMoneyOrderEnum.HandleType.OfflineProcessing.index().equals(apiReq.getBody().getHandleType())){
			                try {
			                    if (UserTransferMoneyOrderService.self().officeProcessing(apiReq.getBody().getTradeNo(),operateInfo)) {
			                        result.setCode(DtoConstants.SUCCESS, null);
			                    }
			                } catch (LogicException e) {
			                    result.setMsg(e.getMessage());
			                }
			            }else if(UserTransferMoneyOrderEnum.HandleType.ManualProcessing.index().equals(apiReq.getBody().getHandleType())){
			                try {
			                    if (UserTransferMoneyOrderService.self().manualProcessing(apiReq.getBody().getTradeNo(),operateInfo)) {
			                        result.setCode(DtoConstants.SUCCESS, null);
			                    }
			                } catch (LogicException e) {
			                    result.setMsg(e.getMessage());
			                }
			            }else{
			                result.setMsg("未知的处理方式");
			            }
		        	}
			    }
	        }
		}
        return result;
    }
}
